/**
 * 
 */
package com.cloudcast.client.controller;

import java.util.Map;

import com.cloudcast.client.presenter.Presenter;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;

/**
 * @author Samuel García Martínez <in0de>
 *
 */
public class RootController extends AbstractController implements ValueChangeHandler {
	
	private static final String DEFAULT_TOKEN = "dashboard";
	private static final String ID = "Root.Controller";
	
	private Presenter rootPresenter;
	
	public RootController(HandlerManager eventBus) {
		super(null, eventBus);		
		
		History.addValueChangeHandler(this);
	}

	@Override
	public LayoutContainer getContainer() {
		return this.getPresenter().getView().asContainer();
	}

	@Override
	public String getId() {
		return ID;
	}

	@Override
	protected void registerResponsibles(Map<String, Responsible> responsibles) {
		Controller dashboardController = new DashboardController(this, getEventBus());
		
		responsibles.put("dashboard", dashboardController);
	}

	@Override
	public void onValueChange(ValueChangeEvent event) {
		String token = event.getValue().toString();
		
		try {
			invokeView(token);
		} catch (ControllerException e) {
			try {
				invokeView(DEFAULT_TOKEN);
			} catch(ControllerException ex) { /* do nothing */ }
		}		
	}

	public void go(LayoutContainer rootPanel) {
		getPresenter().go(rootPanel);
		
		try {
			invokeView(getActualViewId());
		} catch (ControllerException e) {
			History.newItem(DEFAULT_TOKEN);
		}
		
		rootPanel.layout();
	}
	
	@Override
	public void bind(Controller controller) {
		/* RootController is never bound to anything */		
	}

	@Override
	public void unbind(Controller controller) {
		/* RootController is never bound to anything */		
	}

	@Override
	public Presenter getPresenter() {
		if(this.rootPresenter == null)
			this.rootPresenter = new RootPresenter(this, getEventBus());
		
		return this.rootPresenter;
	}
}
